package com.baidu.ai.aip.utils;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.codec.binary.Base64;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class Base64zip {


    /**
     * 压缩base64编码至70k以内
     *
     * @param base64Img
     * @return
     */
    public static String resizeImageTo70K(String base64Img) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes1 = decoder.decodeBuffer(base64Img);
            InputStream stream = new ByteArrayInputStream(bytes1);
            BufferedImage src = ImageIO.read(stream);

            BufferedImage output = Thumbnails.of(src).size(1000, 600).asBufferedImage();
            String base64 = imageToBase64(output);
            if (base64.length() - base64.length() / 8 * 2 > 70000) {
                output = Thumbnails.of(output).scale(1 / (base64.length() / 70000)).asBufferedImage();
                base64 = imageToBase64(output);
            }
            return base64;
        } catch (Exception e) {
            return base64Img;
        }
    }

    /**
     * BufferedImage转换成base64，在这里需要设置图片格式,因为我需要jpg格式就设置了jpg
     */
    public static String imageToBase64(BufferedImage bufferedImage) {
        Base64 encoder = new Base64();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ImageIO.write(bufferedImage, "jpg", baos);
        } catch (IOException e) {
        }
        return new String(encoder.encode((baos.toByteArray())));
    }
}
